package com.tianzeculture.stagebao.activity.personal;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.alipay.PayResult;
import com.tianzeculture.stagebao.activity.home.adapter.BestPushAdapter;
import com.tianzeculture.stagebao.activity.mine.ChooseMoneyAdapter;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.AliBean;
import com.tianzeculture.stagebao.bean.AllIndustryBean;
import com.tianzeculture.stagebao.bean.ArtistsDetailedBean;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.bean.WechatBean;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.L;
import com.tianzeculture.stagebao.util.Util;
import com.tianzeculture.stagebao.view.MyRecyclerview;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.tianzeculture.stagebao.net.base.AppBaseRestUsageV2.PICTURE_URL;

public class RechargeActivity extends BaseActivity implements ChooseMoneyAdapter.OnMoneyListener {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSubtitle)
    TextView tvSubtitle;
    @BindView(R.id.ibtnDelete)
    ImageButton ibtnDelete;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.statusView)
    View statusView;
    @BindView(R.id.ibtnSystemNews)
    ImageButton ibtnSystemNews;
    @BindView(R.id.iv_pi_header)
    CircleImageView ivPiHeader;
    @BindView(R.id.tvUserName)
    TextView tvUserName;
    @BindView(R.id.tvBalance)
    TextView tvBalance;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.layoutHead)
    RelativeLayout layoutHead;
    @BindView(R.id.mRecyclerview)
    RecyclerView mRecyclerview;
    @BindView(R.id.check_ali)
    RadioButton checkAli;
    @BindView(R.id.check_wei)
    RadioButton checkWei;
    @BindView(R.id.tvMoney)
    TextView tvMoney;
    @BindView(R.id.btnSure)
    Button btnSure;

    @Request
    UserRestUsage userRestUsage = null;

    private int myInfo = 101;
    private int rechargeType = 1;
    private int aliId = 5;
    private int wechatId = 6;
    ChooseMoneyAdapter adapter;
    List<String> list = new ArrayList<>();
    String money = "0.01";
    private static final int SDK_PAY_FLAG = 1;
    //    private static final int SDK_AUTH_FLAG = 2;
    private IWXAPI api;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
//                case SDK_AUTH_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
//                    String resultStatus = authResult.getResultStatus();
//
//                    // 判断resultStatus 为“9000”且result_code
//                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
//                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
//                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
//                    } else {
//                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
//
//                    }
//                    break;
            }
        }
    };

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_recharge;
    }


    @Override
    public void initUI() {
        super.initUI();
        tvTitle.setText("充值中心");

        list.add("50");
        list.add("100");
        list.add("200");
        list.add("500");
        list.add("1000");
        list.add("5000");
        mRecyclerview.setNestedScrollingEnabled(false); //解决滑动不流畅
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager
                (3, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setLayoutManager(layoutManager);
        mRecyclerview.setHasFixedSize(true);
        adapter = new ChooseMoneyAdapter(R.layout.item_money, list, this);
        adapter.setListener(this);
        mRecyclerview.setAdapter(adapter);
        userRestUsage.myInfo(myInfo, Util.UserId);
    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == myInfo) {
            if (msg.getData()) {
                ArtistsDetailedBean resultBean = (ArtistsDetailedBean) msg.getObj();
                User user = resultBean.getUser();
                Glide.with(this).load(PICTURE_URL + user.getImgurl()).
                        diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .error(R.mipmap.icon_head)
                        .placeholder(R.mipmap.icon_head)
                        .dontAnimate().into(ivPiHeader);
                tvUserName.setText(user.getNickname());
            }
        }
        if (taskId == aliId) {
            if (msg.getData()) {
                final AliBean bean = (AliBean) msg.getObj();
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        Map<String, String> result = alipay.payV2(bean.getSign(), true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        }
        if (taskId == wechatId) {
            if (msg.getData()) {
                final WechatBean bean = (WechatBean) msg.getObj();
                api = WXAPIFactory.createWXAPI(this, null);
                api.registerApp("wx78a5a1fa6e3fdada");
                try {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            PayReq req = new PayReq();
                            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                            req.appId = bean.getAppid();
                            req.partnerId = bean.getPartnerid();
                            req.prepayId = bean.getPrepayid();
                            req.nonceStr = bean.getNoncestr();
                            req.timeStamp = bean.getTimestamp();
                            req.packageValue = "Sign=WXPay";
                            req.sign = bean.getSign();
//                            req.extData = "app data"; // optional
                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }
                    }).start();
                } catch (Exception e) {
                    Toast.makeText(RechargeActivity.this, "异常", Toast.LENGTH_SHORT).show();
                }

            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.check_ali, R.id.check_wei, R.id.btnSure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_ali:
                checkWei.setChecked(false);
                rechargeType = 1;
                break;

            case R.id.check_wei:
                checkAli.setChecked(false);
                rechargeType = 2;
                break;
            case R.id.btnSure:
                switch (rechargeType) {
                    case 1:
                        userRestUsage.payByAli(aliId, money);
                        break;
                    case 2:
                        userRestUsage.payByWechat(wechatId, money);
                        break;
                }

                break;
        }
    }

    @Override
    public void getMoney(String money) {
        SpannableString spannableString = new SpannableString("应付金额: " + money + "元");
        ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.colorPink));
        spannableString.setSpan(span, 6, spannableString.length() - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvMoney.setText(spannableString);
//        this.money = money;
    }
}
